//
//  WBRefreshView.m
//  OCMicroBlog
//
//  Created by 002 on 15/11/8.
//  Copyright © 2015年 002. All rights reserved.
//

#import "WBRefreshView.h"

@interface WBRefreshView ()

@end

@implementation WBRefreshView

// 刷新视图 - 负责处理`动画显示`
+ (instancetype)refreshView {
    
    // 推荐使用 UINib 的方法是加载 XIB 效率更高
    UINib *nib = [UINib nibWithNibName:@"WBRefreshView" bundle:nil];
    
    return [nib instantiateWithOwner:nil options:nil][0];
}

// 旋转下拉图标动画
- (void)rotateTipIcon {
    
    // 旋转动画的 '就近原则' + '顺时针优先'
    CGFloat angle = M_PI;
    angle += self.rotateFlag ? -0.0000001 : 0.0000001;
    
    [UIView animateWithDuration:0.5 animations:^{
        self.tipIconView.transform = CGAffineTransformRotate(self.transform, angle);
    }];
}

#pragma mark - 动画处理
// ‘下拉’加载数据动画
- (void)startAnimation {
    
    // 执行刷新数据时隐藏 ‘下拉开始刷新’视图
    self.tipView.hidden = true;
    
    NSString *key = @"transform.rotation";
    if ([self.loadingView.layer animationForKey:key]) {
        return;
    }
    
    // 1. 创建动画类型
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:key];
    
    // 2. 设置动画属性
    anim.repeatCount = MAXFLOAT;
    anim.duration = 0.5;
    anim.toValue = @(2 * M_PI);
    anim.removedOnCompletion = false;
    
    // 3. 给控件的图层添加动画
    [self.loadingView.layer addAnimation:anim forKey:key];
    
}

// 停止动画
- (void)stopAnimation {
    
    NSLog(@"停止动画");
    
    // 显示 ‘下拉开始刷新’ 视图
    self.tipView.hidden = false;
    
    // 移除 ‘加载数据’动画
    [self.loadingView.layer removeAllAnimations];
}

- (void)setRotateFlag:(BOOL)rotateFlag {
    _rotateFlag = rotateFlag;
    [self rotateTipIcon];
}

@end
